﻿<?php
require_once 'application/presenters/questions_presenter.php';

class Questions extends CI_Controller{
	public function __construct(){
		parent::__construct();
	}

	public function index(){
		$this->allQuestions();
	}
	
	//Функција за приказ на сите прашања на соодветниот јазик
	public function allQuestions($id=null){
		$this->load->model('questions_model');
		
		$data['title'] = $this->lang->line('questions:questions');
		$data['include'] = 'frontend/content';
		$data['navbar'] = 'frontend/navbar';
		$data['navContent'] = "<a href=". site_url('questions/askQuestion') .">".$this->lang->line('ask')."</a>";
		$data['content'] = 'questions/allQuestions';
		$questions = new questions_presenter($this->questions_model->getAll());
		$data['questions'] = $questions->printAllQuestions(); 
		
		$this->load->view('masterPage', $data);
	}

	//Функција за внесување на прашање во база и валидација на истото
	public function askQuestion(){
		$this->load->helper('form');
		$this->load->library('form_validation');
		$data['validation_message'] = '';
		
		if($this->input->post('submit')){
			$this->load->model('questions_model');
				
			$this->form_validation->set_rules('name', $this->lang->line('questions:name'), 'required|xss_clean');
			$this->form_validation->set_rules('email', $this->lang->line('questions:email'), 'required|xss_clean|valid_email');
			$this->form_validation->set_rules('question', $this->lang->line('questions:question'), 'required|xss_clean');
			$this->form_validation->set_rules('informMe', $this->lang->line('questions:emailMe'), 'xss_clean');
				
			if($this->session->userdata('ln') == 'mk'){
				$this->form_validation->set_message('required', 'Полето %s не смее да биде празно.');
				$this->form_validation->set_message('valid_email', 'Внесениот е-mail не е валиден.');
				$this->form_validation->set_message('xss_clean', 'Имате внесено невалидни карактери во полето %s.');
			}
				
			if ($this->form_validation->run() == FALSE)
			{
				$data['validation message'] = validation_errors();
			}else{
				$name = $this->input->post('name', TRUE);
				$email = $this->input->post('email', TRUE);
				$question = $this->input->post('question', TRUE);
				$informMe = $this->input->post('informMe', TRUE)? 0:1;
				
				$data = array(
							'question' => $question,
							'name' => $name,
							'email' => $email,
							'language' => $this->session->userdata('ln'),
							'inform' => $informMe,
							'dateAdded' => date('Y-m-d')
						);
				
				$this->questions_model->insert($data);

				$data['validation_message'] = $this->lang->line('questions:question_added');
			}		
		};

		$data['title'] = $this->lang->line('questions:questions');
		$data['include'] = 'frontend/content';
		$data['navbar'] = 'frontend/navbar';
		$data['navContent'] = "";
		$data['content'] = 'questions/askQuestion';

		$this->load->view('masterPage', $data);
	}
}